//页面初始化
$(function(){
	initCreateByTitle();
	initTab();
	
	
	var url = window.location.search;
	if(url != ''){
		var loc = url.substring(url.lastIndexOf('=')+1, url.length);
		$("#tt").tabs('select',loc);
	}
	//关闭新增编辑窗口
	$("#closeBtn").click(function() {
		//backendCommon.closeWin("acquisitionConfigWin");
	});
	//关闭配置窗口
	$("#cancelTemplateBtn").click(function() {
		//backendCommon.closeWin("configTemplateWin");
	});
	
	$('#search_btn').bind('click', function(){ 
		queryAcquisitionConfig();
    });  

	$('#addArticle_btn').bind('click', function(){   
		addAriticle();
	});

	$('#sectionSelectId').on('change',function(){
		var locChannelId = $('#sectionSelectId').val();
		if(locChannelId != -1) {
			 var url = mainDomain + "/hy/article/findThemeMapByChannelId.action";
			 $.post(url,{'locChannelId':locChannelId},function(data){
					if(data.success == true){
						var locThemeSlt = '<option value="-1" selected>---请选择---</option>';
						$.each(data.data.themeMap,function(i,v){
							 locThemeSlt += '<option value="'+ i +'">' + v + '</option>';
						});
						$("#sectionThemeId").html(locThemeSlt);
					}
				});
		 }
	});
	
});


//初始化tab
var initTab = function(){
	$('#tt').tabs('add',{    
	    title:'全部资讯',    
	    content:"<table id='tt_table_99' style='padding:20px;margin-top:10px;'></table>",    
	    closable:false,
	    tools:[{
			iconCls:'icon-reload',
			handler:function(){
				initTable(99);
			}
		}]
	});
    
    $('#tt').tabs('add',
    	{    
	    title:'未发布',    
	    content:"<table id='tt_table_0' style='padding:10px;'></table>",    
	    closable:false,
	    tools:[{
			iconCls:'icon-reload',
			handler:function(){
				initTable(0);
			}
		}]
	});
    $('#tt').tabs('add',
    		{    
    	title:'已发布',    
    	content:"<table id='tt_table_3' style='padding:10px;'></table>",    
    	closable:false,
    	tools:[{
    		iconCls:'icon-reload',
    		handler:function(){
    			initTable(3);
    		}
    	}]
    });
    $('#tt').tabs({
    	cache:false,
        border:false,
        fit:true,
        tabHeight:36,
        onSelect:function(title){
        	if (title == '') {
        		initTable(0);
        	}
    		if(title == '全部资讯'){
    			initTable(99);
    		}
    		if(title == '未发布'){
    			initTable(0);
    		}
    		if(title == '已发布'){
    			initTable(3);
    		}
        }
    });
};

function addAriticle() {
	//window.location.href = mainDomain + '/article/initArticle.action';
	backendCommon.openInTabs(mainDomain + '/hy/article/initArticle.action', "新增资讯");
}

//查询
function queryAcquisitionConfig() {
	var sectionSelectIdVal = $('#sectionSelectId').val(),locChannel = '',locTheme='';
	var sectionThemeId = $("#sectionThemeId").val();
	if (sectionSelectIdVal != '-1') {
		locChannel  = sectionSelectIdVal;
	}
	if(sectionThemeId != '-1') {
		locTheme = sectionThemeId;
	}
	if ($.trim($('#createBy').val()) == '') {
		$("#createById").val('');
	}
	$('#tt_table_' + $('#search_tab_index').val()).datagrid('reload', {
		title : $.trim($("#title").val()),
		createBy : $("#createById").val(),
		locChannelId : locChannel,
		locThemeId : locTheme,
		startTimeStr : $.trim($("#startTime").val()),
		endTimeStr : $.trim($("#endTime").val())
	});
}

function intoInfoDetailPage(id){
   window.open(mainDomain+'/hy/article/infoDetailPage/'+id+'.action',"资讯详情",
			"height=620, width=950,toolbar =no, menubar=no, scrollbars=yes, resizable=no, location=no, status=no");
}

//初始化列表页面
function initTable(i) {
	$('#search_tab_index').val(i);
	var sectionSelectIdVal = $('#sectionSelectId').val(),locChannel = '',locTheme='';
	var sectionThemeId = $("#sectionThemeId").val();
	if (sectionSelectIdVal != '-1') {
			locChannel  = sectionSelectIdVal;
	}
	if(sectionThemeId != '-1') {
		locTheme = sectionThemeId;
	}
	if ($.trim($('#createBy').val()) == '') {
		$("#createById").val('');
	}
	
	$('#tt_table_' + i).datagrid({
		//title:'全部资讯',
		width : backendCommon.getWidth(0.94),
		height : backendCommon.getHeight(0.80),
		loadMsg:"数据装载中,请稍等....",
		url:mainDomain+'/hy/article/doQueryArticleList.action?queryStatus=' + i,
		nowrap: false,
		rownumbers:true,
		fitColumns: true,
		pagination:true,
        singleSelect:false,
        pageSize:10,
	    pageNumber:1,          
	    pageList:[10,15,20],
		queryParams : {
			title : $.trim($("#title").val()),
			createBy : $("#createById").val(),
			locChannelId : locChannel,
			locThemeId : locTheme,
			startTimeStr : $.trim($("#startTime").val()),
			endTimeStr : $.trim($("#endTime").val())
		}, 
		columns : [[
		            {field:'id',checkbox:true},    
					{field : 'title',title : '资讯标题',width :$(this).width() * 0.10,align : 'center',
		            	formatter:function(value,rec){
							if (value !== null && value !== '') {
								var count = '<a href="javascript:void(0)" onclick="javascript:intoInfoDetailPage('+ rec.id +')">';
								count +=''+ value +'</a>';
								return count;
							}
						 }
					},
					{field : 'createByName',title : '创建人',width :$(this).width() * 0.08,align : 'center',
					},
					{field : 'createTime',title : '创建时间',width :$(this).width() * 0.12,align : 'center',
						formatter : function(value, rec, index) {
							var str = "";
							if(value != '') {
								str = backendCommon.dateTimeToLocalStringWithSeconds(value);
							}
							return str;
						}
					},
					{field : 'locThemeName',title : '分类',width :$(this).width() * 0.10,align : 'center'},
					{field : 'infoNote',title : '摘要',width :$(this).width() * 0.15,align : 'center'},
					{field : 'infoStatus',title : '状态',width :$(this).width() * 0.07,align : 'center',
						/* 资讯状态 0：未发布，1：发布待审核，2：已审核待发布，3：已发布，4：预约待推送，5：已推送 */
						formatter : function(value, rec, index) {
							var str = '';
							if(value !== '') {
								if (parseInt(value) == 0) {
									str = '未发布';
								} else if (parseInt(value) == 3) {
									str = '已发布';
								} 
							}
							return str;
						}
					},
					{field : 'uid',title : '操作',width : $(this).width() * 0.15,align : 'center',
						 formatter:function(value,rec){
							 var b = '';
							 // if (parseInt(rec.infoStatus) == 0) {
								 // b = '<div><a class="btn_blue06"  id="editbtn" onclick="javascript:publishArticle('+ rec.id +')" href="javascript:void(0)">发布</a></div>';
								 // b += '<div><a class="btn_blue06"  id="editbtn" onclick="javascript:editAritcle('+ rec.id +')" href="javascript:void(0)">编辑</a></div>';
							 // }
							 if (parseInt(rec.infoStatus) == 0 || parseInt(rec.infoStatus) == 3) {
								 b = '<div><a class="btn_blue06"  id="editbtn" onclick="javascript:publishArticle('+ rec.id +')" href="javascript:void(0)">发布</a></div>';
								 b += '<div><a class="btn_blue06"  id="editbtn" onclick="javascript:editAritcle('+ rec.id +')" href="javascript:void(0)">编辑</a></div>';
								 b += '<div><a class="btn_blue06"  id="editbtn" onclick="javascript:deleteAritcle('+ rec.id +')" href="javascript:void(0)">删除</a></div>';
							 }
							 if(rec.locChannelId == 1 && rec.infoStatus == 0 && rec.fileUrl != "1"){
								 b += '<div><a class="btn_blue07" href="javascript:focusNews('+rec.id+')">设为焦点新闻</a></div>';
							 }
							 return b;
						   }
					}
				]]
	});
	
	if (i == 0) {
		$('#tt_table_' + i).datagrid("getPager").pagination({
			buttons: [{
			        	  id:"publishArticlebtn",
			        	  text:"发布",
			        	  iconCls:'icon-redo',
			        	  handler:function(){
			        		  doPublishArticle(i);
			        	  },
			          }]
		});
	}
};

function doPublishArticle(index) {
	var checkrows = $('#tt_table_' + index).datagrid('getChecked');
	if (checkrows.length > 0) {
		var ids = [];
		$.each(checkrows,function(index,item){
			console.log(item.id);
			ids.push(item.id);
		});
		var idsStr = ids.toString();
		$.messager.confirm('确认','确认要发布该资讯？',function(r){    
		    if (r){    
		    	$.ajax({
		    		type : "POST",
		    		url : mainDomain + '/hy/article/batchPublishArticle.action?infoIds=' + idsStr,
		    		dataType:"JSON",
		    		async: false,
		    		success : function(result){
		    			if (result.success) {
		    				$.messager.alert('提示', '发布成功', 'info');
		    				queryAcquisitionConfig();
		    			} else {
		    				$.messager.alert('提示', '服务器开小差了~~，稍后再试试~。', 'error');
		    			}
		    		}
		    	});
		    }    
		}); 
	} else {
		$.messager.alert('提示', '请选择要发布的数据行。', 'error');
	}
}

function editAritcle(id) {
	//window.location.href = mainDomain + '/article/editArticle/'+ id +'.action';
	backendCommon.openInTabs(mainDomain + '/hy/article/editArticle/'+ id +'.action', "编辑资讯");   
}


function focusNews(id) {
	
	$.messager.confirm('确认','确认要设置该文章为焦点新闻？',function(confirm){
		if(confirm){
			$.ajax({
	    		type : "POST",
	    		url : mainDomain + '/hy/article/focusNews/'+ id +'.action',
	    		dataType:"JSON",
	    		success : function(result){
	    			if (result.success) {
	    				queryAcquisitionConfig();
	    			} else {
	    				$.messager.alert('提示', result.message, 'info');
	    			}
	    		}
	    	});
		}
	});
}


function deleteAritcle(id) {
	$.messager.confirm('确认','确认要删除该资讯？',function(r){    
	    if (r){    
	    	$.ajax({
	    		type : "POST",
	    		url : mainDomain + '/hy/article/deleteArticle/'+ id +'.action',
	    		dataType:"JSON",
	    		async: false,
	    		success : function(result){
	    			if (result.success) {
	    				queryAcquisitionConfig();
	    			} else {
	    				$.messager.alert('提示', '服务器开小差了~~，稍后再试试~。', 'error');
	    			}
	    		}
	    	});
	    }    
	}); 
}
function publishArticle(id) {
	$.messager.confirm('确认','确认要发布该资讯？',function(r){    
	    if (r){    
	    	$.ajax({
	    		type : "POST",
	    		url : mainDomain + '/hy/article/publishArticle/'+ id +'.action',
	    		dataType:"JSON",
	    		async: false,
	    		success : function(result){
	    			if (result.success) {
	    				$.messager.alert('提示', '发布成功', 'info');
	    				queryAcquisitionConfig();
	    			} else {
	    				$.messager.alert('提示', '服务器开小差了~~，稍后再试试~。', 'error');
	    			}
	    		}
	    	});
	    }    
	}); 
}

//打开新增对话框
function openAddAcquisitionWin() {
	//初始化窗口
	//清空隐藏属性，栏目ID
	$("#acquisitionConfigId").val("");
	backendCommon.formReset("acquisitionConfigForm");
	backendCommon.openeWin('acquisitionConfigWin');
	$("#saveBtn").unbind('click').click(function() {
		addOrUpdateAcquisitionConfig();
	});
}

//初始化创建人查询
function initCreateByTitle() {
	$("#createBy").autocomplete(mainDomain+"/backend/queryBackendOperatorByName.action", {
		max : 10,
		minChars : 1,
		matchCase : false,
		matchContains : true,
		matchContains : "word",
		scroll : false,
		autoFill : false,
		extraParams : {
			term : function() {
				return $("#createBy").val();
			}
		},
		parse : function(data) {
			var rows = [];
			if (!$.isEmptyObject(data.data)) {
				var operatorList = data.data.rows;
				for(var i = 0;i < operatorList.length;i++) {
					rows[rows.length] = {
							data : operatorList[i],
							value : operatorList[i].realName,
							result : operatorList[i].realName
					};
				}
			} else {
				$("#createById").val('');
			}
			return rows;
		},
		formatItem : function(row, i, max) {
			return   row.realName;
		},
		formatMatch : function(row, i, max) {
			return row.realName;
		},
		formatResult : function(row) {
			return row.realName;
		}
	}).result(function(event, row, formatted) {
		$("#createById").val(row.id);
	});
}
